export default {
  data() {
    return {
      inputText: '',
      messageList: [],
      lastMsgId: '',
      socketTask: null
    }
  },
  onLoad() {
    this.connectWebSocket();
  },
  onUnload() {
    this.socketTask.close();
  },
  methods: {
    // 连接 WebSocket
    connectWebSocket() {
      this.socketTask = uni.connectSocket({
        url: 'wss://work.cnyiji.cn/wss',
        success: () => console.log('Socket Connected')
      });

      // 监听消息
      this.socketTask.onMessage(res => {
        const msg = JSON.parse(res.data);
        this.receiveMessage(msg);
      });
    },

    // 发送消息
    sendMessage() {
      if (!this.inputText.trim()) return;

      const newMsg = {
        content: this.inputText,
        time: this.getCurrentTime(),
        isMe: true
      };

      // 发送到服务器
      this.socketTask.send({
        data: JSON.stringify(newMsg),
        success: () => {
          this.messageList.push(newMsg);
          this.scrollToBottom();
          this.inputText = '';
        }
      });
    },

    // 接收消息
    receiveMessage(msg) {
      this.messageList.push({
        ...msg,
        isMe: false
      });
      this.scrollToBottom();
    },

    // 滚动到底部
    scrollToBottom() {
      this.lastMsgId = 'msg' + (this.messageList.length - 1);
    },

    // 获取当前时间
    getCurrentTime() {
      return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
  }
}